﻿using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class CubeTween : MonoBehaviour
{
    public const float gravity = -98;
    public Vector3 v0;
    public float gravityScale = 1;
    public Vector3 targetPosition;
    private bool isMoving = false;

    public void SetTargetPos(Vector3 fromPos, Vector3 targetPos, float t)
    {
        targetPosition = targetPos;
        v0.x = (targetPos.x - fromPos.x) / t;
        v0.y = (targetPos.y - fromPos.y - .5f * gravity * gravityScale * Mathf.Pow(t, 2)) / t;
        isMoving = true;
    }

    void Update()
    {
        if (isMoving)
        {
            // 计算物体的位移
            var nextPos = transform.localPosition + v0 * Time.deltaTime;
            var dir1 = Vector3.Normalize(targetPosition - transform.localPosition);
            var dir2 = Vector3.Normalize(targetPosition - nextPos);
            if (Vector3.Dot(dir1, dir2) < 0)
            {
                //下次移动将超过目标点
                transform.localPosition = targetPosition;
                isMoving = false;
                Debug.Log("到达目标点");
            }
            else
            {
                transform.localPosition = nextPos;
            }
            v0.y += gravity;
        }
    }
}
